import React, { Component } from 'react';
import { connect } from 'dva';
import { Upload, Icon } from 'antd';
import { Form, Input, Select, Button, Card, Row, Col, message } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Profile.less';

const FormItem = Form.Item;
const { Option } = Select;
// use permission as a parameter

@connect(({ user, loading }) => ({
  user,
  loading: loading.effects['user/fetch'],
}))
@Form.create()
export default class Profle extends Component {
  state = {
    loading: false,
    imageUrl: '',
    hpPicFormat: '',
  };
  componentDidMount() {
    const { currentUser } = this.props.user;
    //console.log('current', this.props.user)
    if (typeof currentUser === 'undefined') {
      this.props.dispatch({
        type: 'user/fetchCurrent',
      });
    } else {
      this.setState({ imageUrl: currentUser.hpPicUrl });
    }
  }

  getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };

  beforeUpload = file => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传jpg或者png格式的图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片必须小于2M!');
    }

    if (isJpgOrPng && isLt2M) {
      let type = 'jpg';
      if (file.type === 'image/png') {
        type = 'png';
      }
      this.setState({ hpPicFormat: type });
      this.getBase64(file, imageUrl =>
        this.setState({
          imageUrl,
          loading: false,
        })
      );
    }
    return false;
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // const { devId } = values;
        // const temp = { ...values };
        // const jsonCont = JSON.stringify(temp);
        // //console.log('values', jsonCont);
        // this.props.dispatch({
        //     type: 'dev/edit',
        //     payload: { devId, jsonCont },
        //     callback: () => {
        //         message.success('编辑设备信息成功！');
        //         // this.props.history.push(`/dashboard/devlist`);
        //     },
        // });
        const { imageUrl, hpPicFormat } = this.state;
        let uploadValues;
        if (hpPicFormat) {
          uploadValues = { ...values, hpPicData: imageUrl, hpPicFormat };
        } else {
          uploadValues = values;
        }
        //console.log('values', uploadValues)
        this.setState({ loading: true });
        this.props.dispatch({
          type: 'user/saveprofile',
          payload: { ...uploadValues },
          callback: () => {
            message.success('保存个人资料成功！');
            this.setState({ loading: false });
            // this.props.history.push(`/dashboard/devlist`);
          },
        });
      }
    });
  };

  render() {
    const { user, form } = this.props;
    //console.log('user', user)
    let {
      userName,
      orgName,
      fullName,
      userId,
      gender,
      licType,
      licNo,
      city,
      regDate,
      roleName,
      mobPhone,
      email,
      fixPhone,
      fax,
      hpPicUrl,
    } = user.currentUser;
    const { getFieldDecorator } = form;

    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">点击上传照片</div>
      </div>
    );
    return (
      <PageHeaderLayout title="编辑用户信息">
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} style={{ marginTop: 8 }}>
            <Row>
              <Col span={12}>
                <FormItem
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 14 }}
                  label="头像："
                  style={{ display: 'flex', alignItems: 'center' }}
                >
                  <Upload
                    name="avatar"
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    beforeUpload={this.beforeUpload}
                  >
                    {this.state.imageUrl ? (
                      <img src={this.state.imageUrl} alt="avatar" style={{ width: '100%' }} />
                    ) : (
                      uploadButton
                    )}
                  </Upload>
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col span={12}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="登录帐号：">
                  <Input defaultValue={userName} disabled />
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="角色名称：">
                  <Input defaultValue={roleName} disabled />
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="用户ID：">
                  <Input defaultValue={userId} disabled />
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="创建时间：">
                  <Input defaultValue={regDate} disabled />
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="姓名：">
                  {getFieldDecorator('fullName', {
                    initialValue: fullName,
                    //  rules: [{ required: true, message: '请输入设备名称...' }],
                  })(<Input />)}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="公司名称：">
                  {getFieldDecorator('orgName', {
                    initialValue: orgName,
                    //  rules: [{ required: true, message: '请输入设备名称...' }],
                  })(<Input />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="证件类型：">
                  {getFieldDecorator('licType', {
                    initialValue: licType,
                  })(
                    <Select allowClear="true" placeholder="请选择" style={{ width: '100%' }}>
                      <Option value={0}>营业执照</Option>
                      <Option value={1}>身份证</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="证件号码：">
                  {getFieldDecorator('licNo', {
                    initialValue: licNo,
                    //  rules: [{ required: true, message: '请输入设备名称...' }],
                  })(<Input />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="性别：">
                  {getFieldDecorator('gender', {
                    initialValue: gender,
                  })(
                    <Select allowClear="true" placeholder="请选择" style={{ width: '100%' }}>
                      <Option value={0}>男</Option>
                      <Option value={1}>女</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="所在城市：">
                  {getFieldDecorator('city', {
                    initialValue: city,
                    //  rules: [{ required: true, message: '请输入设备名称...' }],
                  })(<Input />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="手机号：">
                  {getFieldDecorator('mobPhone', {
                    initialValue: mobPhone,
                    //  rules: [{ required: true, message: '请输入车队名称...' }],
                  })(<Input placeholder="请输入" />)}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="传真：">
                  {getFieldDecorator('fax', {
                    initialValue: fax,
                    //  rules: [{ required: true, message: '请输入公司名称!' }],
                  })(<Input placeholder="请输入" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="邮箱：">
                  {getFieldDecorator('email', {
                    initialValue: email,
                    //  rules: [{ required: true, message: '请输入车队名称...' }],
                  })(<Input placeholder="请输入" />)}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="办公电话：">
                  {getFieldDecorator('fixPhone', {
                    initialValue: fixPhone,
                    //  rules: [{ required: true, message: '请输入公司名称!' }],
                  })(<Input placeholder="请输入" />)}
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col span={24} offset={10}>
                <Button
                  type="primary"
                  htmlType="submit"
                  style={{ width: 200, height: 50 }}
                  loading={this.state.loading}
                  onSubmit={this.handleSubmit}
                >
                  提交
                </Button>
              </Col>
            </Row>
          </Form>
        </Card>
      </PageHeaderLayout>
    );
  }
}
